<template>
	<div class="content">
		<ImportFile ref="importFileRef" />
		<div v-loading="true" v-if="!schema" style="height: 500px;" />
		<amis v-else ref="amisRef" :schema="schema" />
	</div>
</template>

<script setup name="PublicView">
	import amis from '@/components/Amis/index.vue'
	import ImportFile from '@/components/ImportFile'
	import {
		detailsByKey
	} from "@/api/tool/business";
	import {
		getFormData
	} from "@/api/tool/business";
	import store from '@/store'
	import {nanoid} from 'nanoid';
	import {ElMessage} from 'element-plus'
	import {addSchemaFilter} from  "amis-core"
import { onMounted } from 'vue';
	addSchemaFilter((schema,renderer,props)=>{
	  if(schema.actions&&schema.actions[0]&&schema.actions[0].label=="设置查询字段"){
		   schema.actions[0].hidden=true
		   return schema
	  }
	  return schema
	})

	const props = defineProps({
		previewConfig: {
			type: Object,
			defluat: () => null
		},
		businessId: {
			type: String,
			defluat: ''
		}
	}),
	//dom ref
	amisRef = $ref(null),
	importFileRef = $ref(null),
	//数据
	routeName = $ref(null),
	schema = $ref(null),
	config = $ref(null);


	
	const route = useRoute();
			
     //实现不缓存页面			
	watch(route,(newValue,oldValue)=> {
			if(routeName&&schema&&routeName==newValue.name&&newValue.meta.amisNoCache){
				  const temp=schema
				  schema=null
					nextTick(()=>{
					  schema=temp
					})
			}
	})
	

	function getSchema(businessId) {
		detailsByKey(businessId, true).then(res => {
			if (res.code == 200) {
				res.data.schema = JSON.parse(res.data.schemaJson)
				initSchema(res.data)
			}
		})
	}

	function initSchema(config, amisId) {
		if (config.json) {
			const userId = 1 //store.state.user.userId;
			let json = JSON.parse(config.json),
				conditions = json.apiInfo.conditions; //总查询条件
			if (!config.schema.data) {
				config.schema.data = {}
			}

			const amisId = nanoid()
			window.amisTracker = window.amisTracker || {}
			window.amisTracker[amisId] = tracker

			config.schema.data = {
				...config.schema.data,
				sysUser__user_id: userId,
				__roles: [], //store.state.user.roles||
				__amisId: amisId
			}

			if (conditions && Object.keys(conditions).length) {
				if (json.basic.viewType == '1' && JSON.stringify(conditions).indexOf('{user_id}') > -1) {
					config.schema.body[0].api.data.params.user_id = userId
				}
			}
		}
		schema = config.schema
		// console.log(JSON.stringify(schema))
	}

	function getValues(name) {
		let promise = new Promise((resolve, reject) => {
			try {
				amisRef.getValues(name).then(res => {
					resolve(res)
				})
			} catch (e) {
				resolve(null)
			}
		})
		return promise
	}
	//页面行为交互
	function tracker(eventTrack, props) {
		try {
			const {eventType,eventData} = eventTrack
			if (eventType == 'button' && eventData.label == '导入' && eventData.id && eventData.id.indexOf('import__') ===0) {
				//导入功能
				importFileRef.open(JSON.parse(eventData.id.substring(8,eventData.id.length)))
			}
			// if (eventType == 'formItemChange' && eventData.name.indexOf('__search_') === 0 && eventData.type ==
			// 	'checkbox') {
			// 	//设置查询字段时，调用重置
			// 	resetCrud()
			// } 
			
		} catch {}
	}

	// function resetCrud() {
	// 	const btns = document.getElementsByClassName("cxd-Button");
	// 	for (let i = 0; i < btns.length; i++) {
	// 		if (i !== 0 && btns[i - 1].type == 'submit' && btns[i - 1].textContent == '搜索' && btns[i].type == 'reset' &&
	// 			btns[i].textContent == '重置') {
	// 			btns[i].click()
	// 			i = 999999
	// 		}
	// 	}
	// }
	//字段显示权限by Roles
	// getRole(roles){
	//   return `'${roles.join(',')}'.split(',').some(i => {return __roles.indexOf(i)>-1})`
	// },


	onMounted(() => {
		if (props.previewConfig) {
			initSchema(props.previewConfig)
		} else if (props.businessId || route.meta.businessId) {
			routeName = route.name
			getSchema(props.businessId || route.meta.businessId)
		} else {
			ElMessage({
				message: '加载失败',
				type: 'error',
				showClose: true,
				duration: 2000
			})
		}
	})
	defineExpose({
		getValues
	});
</script>
<style lang="scss" scoped>
	.content{
		height: 100%;
	}
	.content > .box:first-child {
		height:100%
	}
</style>